<template>
  <div v-if="loading" class="reportEditOrAdd" style="height： 100vh;">
    <div class="content-box">
      <div v-if="$route.query.reportId" class="report-title">编辑教研报告</div>
      <div v-else class="report-title">上传教研报告</div>

      <div class="teaching-box">
        <div class="title">基本信息</div>
        <el-form
          ref="lessonReportForm"
          :rules="rules"
          class="teaching-form"
          label-width="140px"
          :model="lessonReportForm"
        >
          <el-form-item label="报告标题：" prop="title">
            <el-col :span="12">
              <el-input v-model="lessonReportForm.title" placeholder="请输入标题，如小蝌蚪找妈妈" />
            </el-col>
          </el-form-item>
          <el-form-item label="选择教研活动：">
            <el-col :span="12">
              <el-select
                v-model="lessonReportForm.activityId"
                style="width: 100%;"
                placeholder="请选择教研活动"
              >
                <el-option
                  v-for="(item , index) in options.researchOpt"
                  :key="index"
                  :label="item.title"
                  :value="item.activityId"
                />
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="12">
              <Category
                biz-type-enum="TEACHINGRESEARCH_REPORT"
                :list="lessonReportForm"
                :gutter="20"
                :disabled="$route.query && $route.query.activityId ? true : false"
                @Callback="categoryCallback"
              />
            </el-col>
          </el-form-item>
          <el-form-item
            v-if="lessonReportForm.cateTagsSelect"
            label="教研报告分类："
            prop="cateTagsSelect"
          >
            <el-cascader
              v-model="lessonReportForm.cateTagsSelect"
              style="width: 50%;"
              :options="options.cateTags"
              popper-class="cascaderBox"
              :props="{
                multiple: true,
                value: 'tagsId',
                label: 'tagsName',
                children: 'sub',
                checkStrictly: true
              }"
              placeholder="请选择教研报告分类"
              clearable
              filterable
              @blur.native.capture="getAddCategoryTags($event, 'category')"
              @keyup.enter.native=" getAddCategoryTags($event, 'category')"
            />
          </el-form-item>

          <el-form-item v-if="lessonReportForm.colTagsSelect" label="教研报告标签：" prop="colTagsSelect">
            <el-cascader
              ref="cascaderDom"
              v-model="lessonReportForm.colTagsSelect"
              style="width: 50%"
              placeholder="请选择教研报告标签"
              :options="options.colTags"
              :props="{
                multiple: true,
                checkStrictly: true ,
                label:'tagsName',
                value:'tagsId',
                children: 'sub'
              }"
              clearable
              filterable
              @blur.native.capture="getAddCategoryTags($event, 'tag')"
              @keyup.enter.native=" getAddCategoryTags($event, 'tag')"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="teaching-box">
        <div class="title">文件</div>
        <el-form class="teaching-form" label-width="140px">
          <el-form-item>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                :action="action"
                :header="uploadHeader"
                :data="uploadForm"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
                :file-list="lessonReportForm.fileList"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
              >
                <el-button size="small" icon="el-icon-upload2">上传文件</el-button>
                <div slot="tip" class="el-upload__tip">支持扩展名：.ppt .xls .doc .docx .pdf .jpg...</div>
              </el-upload>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <div class="teaching-box">
        <div class="title">教研介绍</div>
        <el-form class="teaching-form" label-width="140px">
          <el-form-item>
            <editor v-model="lessonReportForm.content" class="marginT40" @input="newContent" />
          </el-form-item>
        </el-form>
      </div>
      <div class="button-box">
        <button v-if="$route.query.reportId" class="submit" @click="onSubmit('lessonReportForm')">保存</button>
        <button v-else class="submit" @click="onSubmit('lessonReportForm')">发布</button>
      </div>
    </div>
  </div>
</template>

<script>
import { preUpload } from '@/api/uploads'
import Category from '@/components/Category'
import { findTagsList } from '@/api/basic'
import { findColumnList, cateTagsGroupFindList } from '@/api/tags'
import { listUnSaveReportTeachingResearch, saveReport, updateReport, getTeachingResearchReport } from '@/api/createResult'
import { getTagsItems, getParents } from '@/utils/categoryOrTags'
import editor from '@/components/Tinymce/index'

export default {
  name: 'ReportEditOrAdd',
  components: {
    editor,
    Category
  },
  data () {
    return {
      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      uploadForm: {},
      options: {
        cateTags: [],
        colTags: [],
        researchOpt: []
      },
      loading: false,
      lessonReportForm: {
        GROWTH_CLASSIFY: {
          cateId: '',
          itemCode: '',
          itemName: ''
        },
        STAGE: {
          cateId: '',
          itemCode: '',
          itemName: ''
        },
        SUBJECT: {
          cateId: '',
          itemCode: '',
          itemName: ''
        },
        title: '',
        activityId: null,
        cateTags: [],
        cateTagsSelect: null,
        colTag: [],
        colTagsSelect: null,
        content: null,
        fileList: [],
        phaseSubjectList: [],
        teachingTarget: [],
        categoryFake: [], // 区分自定义标签
        tagsFake: [] // 区分自定义标签
      },
      rules: {
        title: [
          { required: true, message: '请输入标题!', trigger: 'blur' }
        ],
        colTagsSelect: [
          {
            type: 'array',
            required: true,
            message: '请选择教研报告分类',
            trigger: 'change'
          }
        ],
        cateTagsSelect: [
          {
            type: 'array',
            required: true,
            message: '请选择教研报告标签',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {

  },
  watch: {

  },
  created () {
    // this.lessonReportForm.GROWTH_CLASSIFY = {
    //   cateId: '201',
    //   groupEnum: 'GROWTH_CLASSIFY',
    //   itemCode: '10001',
    //   itemName: '教师成长',
    //   node: true,
    //   pCateId: 0
    // }
    // this.lessonReportForm.STAGE = {
    //   cateId: '20101',
    //   groupEnum: 'STAGE',
    //   itemCode: '1201',
    //   itemName: '学前',
    //   node: false,
    //   pCateId: 0
    // }
    // this.lessonReportForm.SUBJECT = {
    //   cateId: '2010101',
    //   groupEnum: 'SUBJECT',
    //   itemCode: '1128',
    //   itemName: '幼儿教育',
    //   node: true,
    //   pCateId: 0
    // }
    // this.lessonReportForm.activityId = '1286595282338869250'
    // this.lessonReportForm.content = '教研介绍面描述。。。'

    if (this.$route.query && this.$route.query.reportId) {
      this.init()
    } else {
      this.loading = true
    }
  },
  methods: {
    getAddCategoryTags (el, name) {
      var str = el.target.value
      str = str.replace(/\s|，/g, ',')
      str = str.split(',')
      var arr = str.filter(item => item !== '' && item !== ' ')
      var newArr = []
      arr.map(item => {
        newArr.push({
          tagsId: item,
          tagsName: item
        })
      })

      if (name === 'category') {
        this.lessonReportForm.categoryFake = this.lessonReportForm.categoryFake && this.lessonReportForm.categoryFake.length > 0 ? this.lessonReportForm.categoryFake : []
        this.lessonReportForm.cateTagsSelect = this.lessonReportForm.cateTagsSelect.concat(arr)
        this.options.cateTags = this.options.cateTags.concat(newArr)
        this.lessonReportForm.categoryFake = this.lessonReportForm.categoryFake.concat(arr)
      }
      if (name === 'tag') {
        this.lessonReportForm.tagsFake = this.lessonReportForm.tagsFake && this.lessonReportForm.tagsFake.length > 0 ? this.lessonReportForm.tagsFake : []
        this.lessonReportForm.colTagsSelect = this.lessonReportForm.colTagsSelect.concat(arr)
        this.options.colTags = this.options.colTags.concat(newArr)
        this.lessonReportForm.tagsFake = this.lessonReportForm.tagsFake.concat(arr)
      }
      console.log('categoryFake:', this.lessonReportForm.categoryFake)
      console.log('tagsFake:', this.lessonReportForm.tagsFake)
    },
    init () {
      this.loading = false
      getTeachingResearchReport({
        reportId: this.$route.query.reportId
      }).then(res => {
        // 教学对象
        res.data.categoryList.map(item => {
          if (item.groupEnum === 'GROWTH_CLASSIFY') {
            res.data['GROWTH_CLASSIFY'] = item
          }
          if (item.groupEnum === 'STAGE') {
            res.data['STAGE'] = item
          }
          if (item.groupEnum === 'SUBJECT') {
            res.data['SUBJECT'] = item
          }
        })
        res.data.content = res.data.textContent
        if (res.data.fileList && res.data.fileList.length > 0) {
          res.data.fileList.map(item => {
            item.name = item.title
          })
        }

        res.data.activityId = res.data.teachingResearch && res.data.teachingResearch.activityId ? res.data.teachingResearch.activityId : null
        this.loading = true
        this.lessonReportForm = res.data
      })
    },
    categoryCallback (obj) {
      this.$set(this.lessonReportForm, 'GROWTH_CLASSIFY', obj.GROWTH_CLASSIFY)
      this.$set(this.lessonReportForm, 'STAGE', obj.STAGE)
      this.$set(this.lessonReportForm, 'SUBJECT', obj.SUBJECT)
      this.getTagsOptions()
    },
    newContent (val) {
      this.lessonReportForm.content = val
    },

    // 获取标签选项
    async getTagsOptions () {
      // 栏目标签参数
      var colTagsParams = {
        growthClassify: this.lessonReportForm.GROWTH_CLASSIFY.itemCode || null,
        stageList: this.lessonReportForm.STAGE.itemCode || null,
        subjectList: this.lessonReportForm.SUBJECT.itemCode || null
      }
      // 查找栏目标签选项
      await findColumnList(colTagsParams).then(res => {
        this.options.colTags = res.data

        console.log('this.lessonReportForm:', this.lessonReportForm.colTag)
        console.log('this.options.colTags:', this.options.colTags)
        var colTags = []
        if (this.lessonReportForm.colTag && this.lessonReportForm.colTag.length > 0) {
          this.lessonReportForm.colTag.map(item => {
            if (getParents(this.options.colTags, item.tagsId, 'tagsId') !== undefined) {
              colTags.push(getParents(this.options.colTags, item.tagsId, 'tagsId').reverse())
            }
          })
        }

        console.log('colTags:', colTags)
        this.$set(this.lessonReportForm, 'colTagsSelect', colTags)
      })

      // 分类标签参数
      var tagsParams = {
        groupId: null,
        growthClassify: this.lessonReportForm.GROWTH_CLASSIFY.itemCode || null,
        stageList: this.lessonReportForm.STAGE.itemCode || null,
        subjectList: this.lessonReportForm.SUBJECT.itemCode || null,
        tagsBizEnum: 'TEACHINGRESEARCH_REPORT'
      }
      // 分类标签参数
      await cateTagsGroupFindList(tagsParams).then(res => {
        var newArr = []
        res.data.map(item => {
          item.tagsId = item.groupId
          item.tagsName = item.groupName
          item.sub = item.tagsVoList
          if (item.tagsVoList instanceof Array) {
            newArr = newArr.concat(item.tagsVoList)
          }
        })

        this.options.cateTags = res.data
        var cateTags = []
        if (this.lessonReportForm.cateTags && this.lessonReportForm.cateTags.length > 0) {
          this.lessonReportForm.cateTags.map(item => {
            if (getParents(this.options.cateTags, item.tagsId, 'tagsId') !== undefined) {
              cateTags.push(getParents(this.options.cateTags, item.tagsId, 'tagsId').reverse())
            }
          })
        }

        this.$set(this.lessonReportForm, 'cateTagsSelect', cateTags)
      })

      // 教研活动
      await listUnSaveReportTeachingResearch().then(res => {
        this.options.researchOpt = res.data
        this.options.researchOpt.unshift({
          title: this.lessonReportForm.teachingResearch.title,
          activityId: this.lessonReportForm.teachingResearch.activityId
        })
      })
    },

    handleRemove (file, fileList) {
      this.lessonReportForm.fileList = fileList
    },

    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },

    uploadSuccess (res, file) {
      this.lessonReportForm.fileList.push({
        name: file.name,
        url: this.lessonReportForm.filesUrl
      })
    },
    beforeUpload (file) {
      // const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
      // if (!imgStr.test(file.name)) {
      //   this.$message.error('上传格式不对，请重新上传!');
      //   return false;
      // }
      let continueUpload = false
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        }).then(res => {
          this.action = res.data.action
          this.uploadForm = res.data.parameters
          this.lessonReportForm.filesUrl = res.data.uri
          continueUpload = true
          resolve(continueUpload)
        }).catch(err => {
          reject(continueUpload)
        })
      })
    },
    onSubmit (formName) {
      console.log(this.lessonReportForm)
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log('submit!')

          // 分类
          this.lessonReportForm.cateTags = []
          if (this.lessonReportForm.cateTagsSelect && this.lessonReportForm.cateTagsSelect.length > 0) {
            // this.options.cateTags = reduceArr(this.options.cateTags)

            var categorySelect = getTagsItems(this.lessonReportForm.cateTagsSelect, this.options.cateTags)

            categorySelect.map(item => {
              this.lessonReportForm.cateTags.push({
                tagsName: item.tagsName,
                tagsId: item.tagsId
              })
            })

            console.log('this.lessonReportForm.categoryFake:', this.lessonReportForm.categoryFake)
            if (this.lessonReportForm.categoryFake && this.lessonReportForm.categoryFake.length > 0) {
              // 区分自定义标签
              this.lessonReportForm.cateTags.map(item => {
                this.lessonReportForm.categoryFake.map(fake => {
                  if (fake === item.tagsName) {
                    item.tagsId = ''
                  }
                })
              })
            }

            // this.lessonReportForm.cateTagsSelect.map(item => {
            //   var items = this.options.cateTags.filter(cate => cate.tagsId === item[0])[0]
            //   if (items) {
            //     this.lessonReportForm.cateTags.push({
            //       tagsName: items.tagsName,
            //       tagsId: items.tagsId
            //     })
            //   }
            // })
          }

          // 标签
          this.lessonReportForm.colTags = []
          if (this.lessonReportForm.colTagsSelect && this.lessonReportForm.colTagsSelect.length > 0) {
            var colTagsSelect = getTagsItems(this.lessonReportForm.colTagsSelect, this.options.colTags)

            colTagsSelect.map(item => {
              this.lessonReportForm.colTags.push({
                tagsId: item.tagsId,
                tagsName: item.tagsName
              })
            })

            // 区分自定义标签
            if (this.lessonReportForm.tagsFake && this.lessonReportForm.tagsFake.length > 0) {
              this.lessonReportForm.colTags.map(item => {
                this.lessonReportForm.tagsFake.map(fake => {
                  console.log('fake:', fake, item)
                  if (fake === item.tagsName) {
                    item.tagsId = ''
                  }
                })
              })
            }
            console.log('this.lessonReportForm.tagsFake:', this.lessonReportForm.tagsFake)

            // var optionColTags = []
            // this.options.colTags.map(item => {
            //   if (item.tagsVoList && item.tagsVoList.length > 0) {
            //     optionColTags = optionColTags.concat(item.tagsVoList)
            //   }
            // })

            // // optionColTags = reduceArr(optionColTags)
            // this.lessonReportForm.colTagsSelect.map(item => {
            //   var items = optionColTags.filter(colTags =>
            //     colTags.tagsId === item[item.length - 1]
            //   )[0]
            //   if (items) {
            //     this.lessonReportForm.colTags.push({
            //       tagsId: items.tagsId,
            //       tagsName: items.tagsName
            //     })
            //   }
            // })
          }

          // 文件
          var fileList = []
          if (this.lessonReportForm.fileList && this.lessonReportForm.fileList.length > 0) {
            this.lessonReportForm.fileList.map(item => {
              fileList.push({
                title: item.name,
                url: item.url
              })
            })
          }
          var params = {
            activityId: this.lessonReportForm.activityId || null,
            cateTags: this.lessonReportForm.cateTags && this.lessonReportForm.cateTags.length > 0 ? this.lessonReportForm.cateTags : null,
            colTags: this.lessonReportForm.colTags && this.lessonReportForm.colTags.length > 0 ? this.lessonReportForm.colTags : null,
            content: this.lessonReportForm.content || null,
            fileList: fileList || null,
            title: this.lessonReportForm.title || null
          }

          if (this.$route.query && this.$route.query.reportId) {
            params.reportId = this.lessonReportForm.id
            params.teachingTarget = this.lessonReportForm.GROWTH_CLASSIFY && this.lessonReportForm.GROWTH_CLASSIFY.cateId ? this.lessonReportForm.GROWTH_CLASSIFY : null
            params.phase = this.lessonReportForm.STAGE && this.lessonReportForm.STAGE.cateId ? this.lessonReportForm.STAGE : null
            params.subject = this.lessonReportForm.SUBJECT && this.lessonReportForm.SUBJECT.cateId ? this.lessonReportForm.SUBJECT : null

            updateReport(params).then(res => {
              this.$message({
                message: '教研报告更新成功',
                type: 'success'
              })
              // this.$router.push({
              //   path: '/createResult/',
              //   params: {
              //     tabsName: 'Report'
              //   }
              // })
            })
          } else {
            if (this.lessonReportForm.GROWTH_CLASSIFY && this.lessonReportForm.GROWTH_CLASSIFY.cateId) {
              params.teachingTarget = [{
                cateId: this.lessonReportForm.GROWTH_CLASSIFY.cateId,
                groupEnum: this.lessonReportForm.GROWTH_CLASSIFY.groupEnum,
                itemCode: this.lessonReportForm.GROWTH_CLASSIFY.itemCode,
                itemName: this.lessonReportForm.GROWTH_CLASSIFY.itemName
              }]
            } else {
              params.teachingTarget = null
            }
            params.phaseSubjectList = [this.lessonReportForm.STAGE, this.lessonReportForm.SUBJECT]
            saveReport(params).then(res => {
              this.$message({
                message: '教研报告上传成功',
                type: 'success'
              })
              this.$router.push({
                path: '/createResult/',
                params: {
                  tabsName: 'Report'
                }
              })
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
      //       var birthday = new Date("July 21, 1983 01:15:00")
      // document.write(birthday.getDate())
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.avatar-uploader {
  display: inline-block;
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  .icon-text {
    width: 200px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.step {
  span {
    margin: 0 8px;
  }
  .el-input {
    width: 90% !important;
  }
  .step-btn {
    margin-left: 20px;
    margin-top: 10px;
  }
}

.reportEditOrAdd {
  .content-box {
    padding: 40px;
    background: rgba(245, 246, 250, 1);
    .report-title {
      font-size: 20px;
      font-family: MicrosoftYaHei;
      color: rgba(0, 0, 0, 0.85);
      line-height: 28px;
    }

    .teaching-box {
      background-color: white;
      margin-top: 24px;
      padding-bottom: 16px;
      border-radius: 16px;
      .title {
        border-bottom: 1px solid #d9d9d9;
        line-height: 46px;
        padding: 0 40px;
        font-size: 16px;
        font-family: MicrosoftYaHei;
        color: rgba(0, 0, 0, 0.85);
      }

      .teaching-form {
        margin-top: 40px;
        padding: 0 40px;
      }
      .textarea {
        height: 300px;
        padding: 20px;
        background: rgba(0, 0, 0, 0.02);
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
      }
    }
    .button-box {
      margin-top: 24px;
      .submit {
        width: 128px;
        height: 40px;
        border: none;
        background: rgba(84, 184, 123, 1);
        border-radius: 4px;

        font-size: 16px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
        line-height: 24px;
        cursor: pointer;
      }
    }
  }
}
</style>
